<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>debounce</title>
    <style>
        #container {
            width: 100%;
            height: 200px;
            line-height: 200px;
            text-align: center;
            color: #fff;
            background-color: #444;
            font-size: 30px;
        }
    </style>
</head>

<body>
    <h2>debounce 防抖函数</h2>
    <p>
        应用的场景：
        <li>
            1window 的 resize、scroll
        </li>
        <li>
            mousedown、mousemove
        </li>
        <li>
            keyup、keydown
        </li>

    </p>
    <button id="btn">点击</button>
    <p>
        防抖函数的原理：你尽管触发函数，但是我一定会在这段时间过后才执行函数，如果在此时间之内又触发了函数，就会重置定时器，重新开始计时。总而言之，就是要等你触发完事件 n 秒内不再次触发我才执行。
    </p>
    <div id="container"></div>
    <script>
        var count = 1;
        var container = document.getElementById('container');

        function getUserAction() {
            container.innerHTML = count++;
        };
        container.onmousemove = debounce(getUserAction, 2000);
        // 实现一个debounce函数
        function debounce(fn, wait) {
            var timeOut;
            return function () {
                var context = this
                var args = arguments
                clearTimeout(timeOut)
                timeOut = setTimeout(function () {
                    fn.apply(this, args)
                }, wait)
            }
        }

        function debounce(fn, wait) {
            var timer
            return function () {
                var context = this
                var args = arguments
                clearTimeout(timer)
                timer = setTimeout(function () {
                    fn.apply(this, arguments)
                }, wait)
            }
        }




        function debounce(fn, wait) {
            var timer;
            return function () {
                clearTimeout(timer)
                timer = setTimeout(() => {
                    fn.apply(this, arguments)
                }, wait)
            }
        }

        function thorttle(fn, wait) {
            var timer = null
            return function () {
                if (!timer) {
                    setTimeout(() => {
                        fn.apply(this, arguments)
                        timer = null
                    }, wait)
                }
            }
        }

        var array1 = [12, "foo", { name:"Joe"}, -2458];
        var array2 = ["Doe", 555, 100];
        Array.prototype.push.apply(array1, array2);
        console.log(array1)
    /* array1 值为  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
    </script>
</body>

</html>
